import React, { useEffect, useMemo, useState } from "react";
import {
  Empty,
  Spin,
  Table,
  Tooltip,
} from 'antd'
import './style.less'
import { useCurrentNode } from "@/hooks/useCurrentNode";
import { useNodesData } from "@xyflow/react";
import { FIELD_TYPE_MAP } from "@/constant/icons";
import useDesignerStore from "@/store/Designer";
import { getFlowData } from "@/api";
import { useGraph } from "@/hooks/useGraph";
import { normalizeFieldType } from "@/utils/dataflow";
import S2Table from "../../common/S2Table";

export const DataSourceResultData = () => {
  const currentNode = useCurrentNode()
  const nodeData = useNodesData(currentNode?.id)
  const [datasource, setDatasource] = useState([])
  const [headers, setHeaders] = useState([])
  const { drawerHeight,drawerLeftWidth } = useDesignerStore()
  const graphData = useGraph()
  const [loading, setLoading] = useState(false)

  const fetchData = () => {
    const data = {
      name: '测试',
      type: 'dag',
      subtype: 'sql',
      system: 'gauss',
      graphData,
      // filterJS: meta.filterJS,
      // indPrivacy: meta.indPrivacy,
      // system: meta.system,
      // variables: meta.variables,
      sqlMaxRows: 100,
      // sameWithDB: meta.sameWithDB,
      // languageType: meta.languageType,
    };
    const ms = {
      message: JSON.stringify(data),
      node: "SQL数据读入",
    }
    setLoading(true)
    getFlowData(ms).then(res => {
      const { columns, data } = res?.data ?? {}
      setDatasource(data ?? [])
      setHeaders(columns)
    }).finally(()=>{
      setLoading(false)
    })
  }
  useEffect(() => {
    if (nodeData?.data?.columns?.length) {
      fetchData()
    }else {
      setHeaders([])
      setDatasource([])
    }
  }, [nodeData])

  const computedColumns = useMemo(() => {
    return headers?.map(record => {
      const columnType = normalizeFieldType(record?.s_type)
      const TypeIcon = FIELD_TYPE_MAP[columnType]?.icon ?? FIELD_TYPE_MAP.unknown.icon
      const TypeLabel = FIELD_TYPE_MAP[columnType]?.label ?? columnType
      return {
        key: record?.name,
        title: <div>
          {record?.name}<br />
          <Tooltip title={TypeLabel}> {TypeIcon}</Tooltip>
        </div>,
        dataIndex: record?.name,
        width: '20%',
        columnType
      }
    }).concat({
      key: 'unk',
      width: 3,
      fixed: 'right',
    })
  }, [headers])

  const computedData = useMemo(() => {
    return datasource?.map(item => {
      if (!Array.isArray(item)) return item
      return item.reduce((acc, cur, idx) => {
        acc[computedColumns?.[idx]?.dataIndex] = cur
        return acc
      }, {})
    })
  }, [datasource, computedColumns])

  const rowClassName = (_, idx) => idx % 2 ? 'even-row' : 'odd-row'

  if (!nodeData?.data?.columns?.length) {
    return <Empty description='未勾选字段' />
  }
    return <Spin spinning={loading}>
      <S2Table dataSource={computedData} columns={computedColumns} height={drawerHeight - 120} />
    </Spin>

  return <Table columns={computedColumns}
    dataSource={computedData}
    className="ds-table"
    size="small"
    virtual
    sticky
    rowClassName={rowClassName}
    scroll={{
      y: drawerHeight - 190,
      x: window.innerWidth - drawerLeftWidth
    }}
    style={{width: 'calc(100% - 10px)'}}
    pagination={false}
    loading={loading}
  />
}